package bom.example.common.excetion;

import bom.example.common.common.Results;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import java.nio.file.AccessDeniedException;
import java.util.List;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/6 1:45
 * @since JDK 1.8
 */
@ControllerAdvice
@Slf4j
@Configuration
public class GlobalExcetion {


    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public JSONObject exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常！原因是:",e);
        JSONObject object=new JSONObject();
        object.put("msg",e);
        return object;
    }

    /**
     * 校验组件使用
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public JSONObject serviceHandle(MethodArgumentNotValidException e) {
        log.info("有异常");
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();
        allErrors.forEach(objectError -> stringBuilder.append(objectError.getDefaultMessage()).append(";"));
        log.info(stringBuilder.toString());
        return Results.error(stringBuilder.toString());
    }


    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JSONObject validatedBindException(BindException e){
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return Results.error(message);
    }


    @ExceptionHandler(ResultExcetion.class)
    @ResponseBody
    public JSONObject resultException(ResultExcetion e){
        return Results.error(e.getCode(),e.getMsg());
    }

}
